import {Page} from '@/base/Page';
import {deleteAffiliate, getAffiliateList} from '@/base/api/AffiliateApi';
import {Affiliate} from '@/base/model/Affiliate';
import {isEmpty} from '@/base/util/Strings';

class Form {
  nickname = '';
  createBegin = '';
  createEnd = '';
  date = [];
}

export class DetailBloc {
  form = new Form();

  paged: Page<Affiliate> = new Page<Affiliate>([], 0, 1, 15, 0, []);
  loading = false;
  memberId = 0;
  isShowDetailModal = false;
  detailMemberId = 0;

  load(pageIndex: number, pageSize: number) {
    if (!isEmpty(this.form.date) && !isEmpty(String(this.form.date[0]))) {
      // @ts-ignore
      this.form.createBegin = this.form.date[0].getTime() || '';
      // @ts-ignore
      this.form.createEnd = this.form.date[1].getTime() + 24 * 60 * 60 * 1000 || '';
    }
    this.loading = true;
    return getAffiliateList({
      pageIndex,
      pageSize,
      memberId: this.memberId,
      nickname: this.form.nickname,
      createBegin: this.form.createBegin,
      createEnd: this.form.createEnd
    }).then((res) => {
      this.paged = res.data;
    }).finally(() => {
      this.loading = false;
    });
  }

  removeItem(dateItem: Affiliate) {
    this.loading = true;
    return deleteAffiliate(dateItem.id)
      .finally(() => {
        this.loading = false;
      });
  }

  reset() {
    this.form = new Form();
    this.paged.pageIndex = 1;
    this.paged.pageSize = 15;
    this.load(this.paged.pageIndex, this.paged.pageSize);
  }

  changeDetailModal(id: number) {
    this.isShowDetailModal = !this.isShowDetailModal;
    this.detailMemberId = id;
    if (!this.isShowDetailModal) {
      this.load(this.paged.pageIndex, this.paged.pageSize);
    }
  }

}
